package com.microtf.inscription.framework.service;

import com.microtf.inscription.framework.pojo.wechat.listener.WeChatMinDbRecord;
import com.microtf.inscription.framework.pojo.wechat.resource.Token;
import com.microtf.inscription.jpa.entity.MiniApp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信消息交互服务
 * 类主要包含用户关注，取消关注，扫码
 * 和发送消息接口接口。
 * 用户只需要实现消息接口就能实现交互
 *
 * @author guliuzhong
 */
@Service
@Slf4j
public class WeChatMiniService extends WeChatServiceBase {
    /**
     * 微信小程序云开发数据导入
     * @param collection 云平台collection
     * @param weChatMinDbRecord 数据库记录序列化实现
     */
    public void addDbRecord(String collection, WeChatMinDbRecord weChatMinDbRecord) {
        MiniApp miniApp = miniAppThreadLocal.get();
        Token token = getToken();
        Map<String,String> getParment=new HashMap<>(1);
        getParment.put("access_token",token.getAccessToken());
        NetService netService = this.netService.newRequest().setUrl("https://api.weixin.qq.com/tcb/databaseadd" ,getParment);
        StringBuilder stringBuilder=new StringBuilder();
        stringBuilder.append("{\"env\":\"").append(miniApp.getCloudEnv()).append("\",");
        stringBuilder.append("\"query\":").append("\"db.collection(\\\"").append(collection).append("\\\").add({");
        stringBuilder.append("data: [{");
        stringBuilder.append(weChatMinDbRecord.data2JsonQuote());
        stringBuilder.append("}]");
        stringBuilder.append("})\"}");
        netService.setJson(stringBuilder.toString());
        String s = netService.requestToString();
        log.info("WeChatMini add record {}",s);
    }
}